package com.sctvcloud.zhaohua_sd.ui.manager;

import android.content.Context;
import android.graphics.Bitmap;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;

import com.jiongbull.jlog.JLog;
import com.ruihang.generalibrary.utils.ListUtils;
import com.ruihang.generalibrary.utils.SharedPreferencesUtil;
import com.sctvcloud.zhaohua_sd.beans.AdPicItem;
import com.sctvcloud.zhaohua_sd.beans.ImageUr;
import com.sctvcloud.zhaohua_sd.http.AbsNetCallBack;
import com.sctvcloud.zhaohua_sd.http.NetUtils;
import com.sctvcloud.zhaohua_sd.ui.activities.SplashActivity;
import com.sctvcloud.zhaohua_sd.utils.LocalUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Author: create by zhangyong on 2018/6/26 14 02
 * Des: 启动页广告定时获取更新
 */
public class AdPictureManager {

    public static final String AD_IMG_PATH = "SCAdPic";
    public static final String AD_IMG_SHOW_TIME = "ad_img_show_time";
    private static final String IMG_URL = "sctv/startPage.json";
    private static final long se = 5 * 60 * 1000;//循环获取的时间间隔
    private Context context;
    private DownLoadImage downLoadImage;
    private ArrayList<Object> adImgs;
    private List<String> localFiles = new ArrayList<>();
    private int time;
    private int msgKey;
    private Timer readyTimer;

    public AdPictureManager(Context context) {
        this.context = context;
    }

    /**
     * 启动广告定时更新服务
     */
    public void startAdService(final Handler mHandler, int key) {
        try {
            msgKey = key;
            readyTimer = new Timer(true);
            Date d1 = new Date();
            readyTimer.schedule(new TimerTask() {
                @Override
                public void run() {
                    Message msg = new Message();
                    msg.what = msgKey;
                    mHandler.sendMessage(msg);
                }
            }, d1, se);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 请求图片路径，并判断本地是否已经存在该图片
     * @param owner
     */
    public void requestAdPic(String owner) {
        final String imgPath = LocalUtils.getSDPath() + "/" + AdPictureManager.AD_IMG_PATH;
        try {
            localFiles = getFileList(imgPath);
        } catch (Exception e) {
            e.printStackTrace();
        }
        NetUtils.getNetAdapter().getAdList(owner, IMG_URL, new AbsNetCallBack<AdPicItem>(AdPicItem.class) {
            @Override
            public void onSuc(AdPicItem adPicItem) {

                if (adPicItem != null && ListUtils.isListValued(adPicItem.getChannel())) {
                    AdPicItem.ImageListItem listItem = adPicItem.getChannel().get(0);
                    if (ListUtils.isListValued(listItem.getImageList())) {
                        adImgs = new ArrayList<>();
                        for (ImageUr imageUr : listItem.getImageList()) {
                            adImgs.add(imageUr.getImageUrl());
                        }
                        if (null != localFiles && localFiles.size() > 0) {
                            for (int k = 0; k < localFiles.size(); k++) {
                                String name = localFiles.get(k);
                                File file = new File(imgPath + "/" + name);
                                if (file.exists()) {
                                    if (null == adImgs || adImgs.size() == 0) {
                                        file.delete();
                                    } else {
                                        for (int l = 0; l < adImgs.size(); l++) {
                                            String adName = DownLoadImage.getPicName(adImgs.get(l).toString());
                                            if (adName.equalsIgnoreCase(name)) {
                                                break;
                                            } else if (l == adImgs.size() - 1) {
                                                file.delete();
                                            }
                                        }
                                    }
                                }
                            }

                        }
                        if (null != adImgs && adImgs.size() > 0) {
                            for (int l = 0; l < adImgs.size(); l++) {
                                String adName = DownLoadImage.getPicName(adImgs.get(l).toString());
                                if (null != localFiles && localFiles.size() > 0) {
                                    for (int k = 0; k < localFiles.size(); k++) {
                                        String name = localFiles.get(k);
                                        if (adName.equalsIgnoreCase(name)) {
                                            break;
                                        } else if (k == localFiles.size() - 1) {
                                            downLoadAd(adImgs.get(l).toString());
                                        }
                                    }
                                } else {
                                    downLoadAd(adImgs.get(l).toString());
                                }
                            }

                        }

                    }
                    time = listItem.getShowTime();
                    SharedPreferencesUtil.setParam(context, AD_IMG_SHOW_TIME, time);
                }
            }

            @Override
            public void onError(Throwable ex, String errorMsg) {
                super.onError(ex, errorMsg);
            }
        });
    }

    /**
     * 下载图片并保存
     * @param url
     */
    private void downLoadAd(String url) {
        if (!TextUtils.isEmpty(url)) {
            new DownLoadImage(context, url, new ImageDownLoadCallBack() {
                @Override
                public void onDownLoadSuccess(Bitmap bm) {

                }

                @Override
                public void onDownLoadSuccess(String picUrl) {
                }

                @Override
                public void onDownLoadFailed() {

                }
            }).run();
        }
    }

    /**
     * 读取制定服务地址的资源文件名称
     *
     * @param path
     * @return
     * @throws Exception
     */
    public synchronized List<String> getFileList(String path) throws Exception {
        List<String> items = new ArrayList<String>();
        File f = new File(path);
        File[] files = f.listFiles();
        if (null != files && files.length >= 0) {
            for (int i = 0; i < files.length; i++) {
                File file = files[i];
                items.add(file.getName());
            }
            System.out.println("服务器文件数" + files.length);
        }
        return items;
    }

}
